var express = require('express');
var router = express.Router();
var request = require('request');
var async = require('async');
var sha1 = require('sha1');

var access_token = null;
var jsapi_ticket = null;
var signature = null;

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: '薇薇的V-Show' });
});

router.get('/wx/token', function (req, res) {
  request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx5253a3f0eb223fe4' +
      '&secret=a03f7b938ba9b32b35f32fa796e672fc', function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log(body);
      res.json(body);
    }
  });
});

router.get('/wx/signature', function (req, res) {
  var timestamp = req.query.timestamp;
  console.log(timestamp);
  var nonceStr = req.query.nonceStr;
  var url = req.query.url;
  async.series([
    function(callback){
      request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx5253a3f0eb223fe4' +
          '&secret=a03f7b938ba9b32b35f32fa796e672fc', function (error, response, body) {
        if (!error && response.statusCode == 200) {
          access_token = JSON.parse(body).access_token;
          console.log("access_token:"+access_token);
          callback(null, body);
        }
      })
    },
    function(callback){
      request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+access_token+'&type=jsapi',
          function (error, response, body) {
            if (!error && response.statusCode == 200) {
              jsapi_ticket = JSON.parse(body).ticket;
              console.log("jsapi_ticket:"+jsapi_ticket);
              callback(null, jsapi_ticket);
            }
      })
    }
  ],function(err, results) {
    //向后台发送signature；
    var string1 = 'jsapi_ticket='+jsapi_ticket+'&noncestr='+nonceStr+'&timestamp='+timestamp+'&url='+url;
    signature = sha1(string1);
    console.log("signature:"+signature);
    res.json(signature);
  });
});

module.exports = router;
